package com.ruicar.afs.cloud.afscase.cargpsmanage.controller;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.cargpsmanage.condition.CarGpsApplyCondition;
import com.ruicar.afs.cloud.afscase.cargpsmanage.entity.CarGpsApply;
import com.ruicar.afs.cloud.afscase.cargpsmanage.service.CarGpsApplyService;
import com.ruicar.afs.cloud.afscase.cargpsmanage.service.CarGpsDeviceService;
import com.ruicar.afs.cloud.afscase.cargpsmanage.service.GpsManageService;
import com.ruicar.afs.cloud.afscase.cargpsmanage.vo.CarGpsApplyVO;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCarInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseContractInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseContractInfoService;
import com.ruicar.afs.cloud.afscase.loanapprove.condition.LoanApproveCondition;
import com.ruicar.afs.cloud.afscase.cargpsmanage.entity.CarGpsDevice;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.ApproveLoanInfoService;
import com.ruicar.afs.cloud.bizcommon.gps.feign.GpsOLEFeign;
import com.ruicar.afs.cloud.bizcommon.gps.service.GpsOLEService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.GpsStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractStatusEnum;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yk.Li
 * @description gps管理控制层
 * @date 2020/5/18 17:39
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/carGpsManage")
@Api("gps管理")
public class CarGpsManageController {

    private final CarGpsApplyService carGpsApplyService;

    private final CarGpsDeviceService carGpsDeviceService;

    private final GpsManageService gpsManageService;

    private ComAttachmentFileService comAttachmentFileService;

    private final CaseContractInfoService caseContractInfoService;

    private final ApproveLoanInfoService approveLoanInfoService;

    private GpsOLEService gpsOLEService;
    /**
     * Mapper获取GPS管理数据
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getGpsManageInfoList")
    @ApiOperation(value = "多条件分页获取GPS管理数据")
    public IResponse<IPage<CarGpsApplyVO>> getGpsManageInfoList(@ModelAttribute QueryCondition condition) {
        CarGpsApplyCondition carGpsApplyCondition = JSONObject.parseObject(
                Convert.toStr(condition.getCondition()), CarGpsApplyCondition.class);
        carGpsApplyCondition.setApproveStaff(SecurityUtils.getUser().getUsername());
        IPage<CarGpsApplyVO> pageResult = carGpsApplyService.getCarGpsApplyInfoList(
                new Page(condition.getPageNumber(), condition.getPageSize()), carGpsApplyCondition);
        return IResponse.success(null != pageResult ? pageResult : "");
    }

    /**
     * 通过合同号获取GPS设备信息
     * @param condition
     * @return
     */
    @PostMapping(value = "/getGpsDeviceInfoList")
    @ApiOperation(value = "通过合同号获取GPS设备信息")
    public IResponse<IPage<CarGpsDevice>> getGpsDeviceInfoList(@ModelAttribute LoanApproveCondition condition) {
        IPage<CarGpsDevice> pageResult = carGpsDeviceService.page(new Page(condition.getPageNumber(),condition.getPageSize())
                , Wrappers.<CarGpsDevice>query().lambda().eq(StringUtils.isNotBlank(condition.getContractNo()),CarGpsDevice::getContractNo,condition.getContractNo()));
        return IResponse.success(null != pageResult ? pageResult : "");
    }

    /**
     * GPS审核流程提交
     * @param condition
     * @return
     */
    @PostMapping(value = "/gpsManageSubmit")
    @ApiOperation(value = "GPS流程提交")
    public IResponse<Boolean> gpsManageSubmit(@ModelAttribute LoanApproveCondition condition) {
        //更新Gps审核状态为审核通过
        gpsManageService.updateStatus(condition.getContractNo(), AfsEnumUtil.key(GpsStatusEnum.PASS_AUDIT) ,null);
        //推送数据到进件系统
        approveLoanInfoService.sendToApplyNotic(condition.getContractNo(), AfsEnumUtil.key(GpsStatusEnum.PASS_AUDIT));
        //流程提交
        // gpsManageService.gpsManageSubmit(condition , AfsEnumUtil.key(GpsStatusEnum.PASS_AUDIT));
        return new IResponse<Boolean>().setMsg("提交成功");
    }

    /**
     * GPS流程退回合作商
     * @param condition
     * @return
     */
    @PostMapping(value = "/backPartnersSubmit")
    @ApiOperation(value = "GPS流程退回合作商")
    public IResponse<Boolean> backPartnersSubmit(@ModelAttribute LoanApproveCondition condition) {
        // 先去查询这个合同有没有激活，如果激活必须是资产修正的才可以
        List<CaseContractInfo> contractInfo =caseContractInfoService.list(Wrappers.<CaseContractInfo>query().lambda().eq(CaseContractInfo::getContractNo,condition.getContractNo()));
        if(contractInfo.size()>0){
            for(CaseContractInfo info:contractInfo ){
                if(ContractStatusEnum.contractEffective.toString().equals(info.getContractStatus().toString())){
                    throw new AfsBaseException("合同已生效，不可以退回！");
                }
            }
        }else {
            throw new AfsBaseException("获取合同信息失败！");
        }
        List<CarGpsApply> applyList =carGpsApplyService.list(Wrappers.<CarGpsApply>query().lambda().eq(CarGpsApply::getContractNo,condition.getContractNo()));
        for(CarGpsApply carGpsApply:applyList){
            // 再去调用GPS退回接口
            JSONObject result = gpsOLEService.cancelOrderWithVpsInfos(carGpsApply.getCarId().toString());
            if(result.getBoolean("Success")){

            }else {
                throw new AfsBaseException("退回GPS失败！"+result.getBoolean("AllMessages"));
            }
        }

        //流程退回
        gpsManageService.backPartnersSubmit(condition);
        return new IResponse<Boolean>().setMsg("提交成功");
    }

    @Transactional
    @PostMapping("/getAllOrderInfoByAppCode")
    @ApiOperation(value = "获取gps工单信息")
    public IResponse getAllOrderInfoByAppCode(@ModelAttribute LoanApproveCondition condition) {
        //查询工单信息并更新设备信息
        if (gpsManageService.getAllOrderInfoByAppCode(condition.getContractNo())) {
            //  再去根据合同获取下这个GPS信息
            CarGpsApply gpsApply =carGpsApplyService.list(Wrappers.<CarGpsApply>query().lambda().eq(CarGpsApply::getContractNo,condition.getContractNo())).get(0);
            return new IResponse().setMsg("GPS信息刷新成功").setData(gpsApply);
        } else {
            return new IResponse().setMsg("GPS信息刷新失败");
        }
    }

    @PostMapping("/getGpsImage")
    @ApiOperation(value = "获取gps影像信息")
    public IResponse getGpsImage(@ModelAttribute LoanApproveCondition condition) {
        CarGpsApply gpsInfo = carGpsApplyService.getOne(Wrappers.<CarGpsApply>query().lambda()
                .eq(CarGpsApply::getApplyNo, condition.getApplyNo()));
        List<ComAttachmentFile> fileList =comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,gpsInfo.getContractNo()).eq(ComAttachmentFile::getBelongNo,gpsInfo.getCarId()));
        return new IResponse().setData(fileList);
    }
}
